//
//  ZAddSchedulingViewController.m
//  Medicare
//
//  Created by LYY on 2017/8/9.
//  Copyright © 2017年 medicare. All rights reserved.
//

#import "ZAddSchedulingViewController.h"
#import "IFMySchedulingPublicDefines.h"
#import "ZAddTableViewCell.h"
#import "UIView+AddLine.h"
#import "ZSchedulingTypeModel.h"

@interface ZAddSchedulingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;

@end

@implementation ZAddSchedulingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   MyNavbar *nav = [[MyNavbar alloc] initWithTitle:@"编辑班次" Image:nil rightTitle:@"完成" andController:self];
    [nav show];
    
    nav.rightBlock = ^{
        
        for (ZSchedulingTypeModel *model in self.dataArray) {
            if ([Common isBlankString:model.className]) {
                [SVProgressHUD showTextHUD:@"班次名称不能为空"];
                return ;
            }
        }
        [SVProgressHUD showWithStatus:@"加载中"];
        [[IFly_APIManager shareManager] api_createOrEditClassInfoWithArray:[ZSchedulingTypeModel mj_keyValuesArrayWithObjectArray:self.dataArray] andBackBlock:^(BackDataVO *data, NSError *error) {
            [SVProgressHUD dismiss];
            if ([data.s isEqualToString:@"1"]) {
                NSArray *dataArrays = [ZSchedulingTypeModel mj_objectArrayWithKeyValuesArray:data.r];
                if ([self.delegate respondsToSelector:@selector(saveSchedulingClassDidCompleteArray:)]) {
                    [self.delegate saveSchedulingClassDidCompleteArray:dataArrays];
                }
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                [SVProgressHUD showTextHUD:data.em];
            }
        }];
    };
    [self.view addSubview:self.tableView];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
     [self setAutomaticallyAdjustsScrollViewInsets:NO];
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self requestDataList];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (!self.dataArray || self.dataArray.count == 0 || indexPath.row == self.dataArray.count) {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 44, 44)];
        [cell addSubview:addButton];
        
        if (indexPath.row >= 10) {
            [addButton setBackgroundImage:IMAGE(@"scheduleImage.bundle/scheduling_add") forState:UIControlStateNormal];
            [addButton addTarget:self action:@selector(addSchedulingNotice) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [addButton addTarget:self action:@selector(addScheduling) forControlEvents:UIControlEventTouchUpInside];
            [addButton setBackgroundImage:IMAGE(@"scheduleImage.bundle／scheduling_add_use") forState:UIControlStateNormal];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 54, kScreenWidth, 1)];
        [line setBackgroundColor:[UIColor colorWithHexString:@"cccccc"]];
        [cell addSubview:line];
        return cell;
    }
    ZSchedulingTypeModel *model = self.dataArray[indexPath.row];
    ZAddTableViewCell *cell = (ZAddTableViewCell *)[tableView dequeueReusableCellWithIdentifier:NSStringFromClass(ZAddTableViewCell.class) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    cell.deleteBlock = ^{
    
        if (model.classInfoId.length > 0) {
            [self deleteWithScheduling:model andIndex:indexPath.row];
        } else {
            [self.dataArray removeObjectAtIndex:indexPath.row];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
        
        
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
}

- (void)addSchedulingNotice {
    [SVProgressHUD showTextHUD:@"最多添加10个班次，请先长按删除不用班次"];
}

- (void)addScheduling {
    [self.view endEditing:YES];
    ZSchedulingTypeModel *addModel = [[ZSchedulingTypeModel alloc] init];
    addModel.deptCode = [UserService share].currentAccount.selectedDeptCode;
    addModel.className = @"";
    addModel.color = @"01";
    addModel.classInfoId = @"";
    
    [self.dataArray addObject:addModel];
    [self.tableView reloadData];
}

#pragma -Lazy loading
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, IFLY_kNavBarHeight, kScreenWidth, kScreenHeight - IFLY_kNavBarHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass(ZAddTableViewCell.class) bundle:nil] forCellReuseIdentifier:NSStringFromClass(ZAddTableViewCell.class)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


#pragma mark - 键盘通知
-(void)keyboardChangeFrame:(NSNotification*)noti {
    CGRect rect= [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat keyboardheight = rect.size.height;
    CGFloat duration=[noti.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat curve=[noti.userInfo[UIKeyboardAnimationCurveUserInfoKey]doubleValue];
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
        if (rect.origin.y == kScreenHeight) {
            self.tableView.height = kScreenHeight - IFLY_kNavBarHeight;
        } else {
            self.tableView.height = kScreenHeight - IFLY_kNavBarHeight - keyboardheight;
        }
    }];
}

#pragma mark - 网络请求
- (void)requestDataList {
    [SVProgressHUD showWithStatus:@"加载中"];
    [[IFly_APIManager shareManager] api_getClassInfoWithDeptCode:[UserService share].currentAccount.selectedDeptCode andBackBlock:^(BackDataVO *data, NSError *error) {
        [SVProgressHUD dismiss];
        if ([data.s isEqualToString:@"1"]) {
            self.dataArray = [ZSchedulingTypeModel mj_objectArrayWithKeyValuesArray:data.r];
            [self.tableView reloadData];
        } else {
            [SVProgressHUD showTextHUD:data.em];
        }
    }];
}

- (void)deleteWithScheduling:(ZSchedulingTypeModel *)model andIndex:(NSInteger)row{
    [SVProgressHUD showWithStatus:@"删除中"];
    [[IFly_APIManager shareManager] api_deleteClassInfoWithId:model.classInfoId andBackBlock:^(BackDataVO *data, NSError *error) {
        [SVProgressHUD dismiss];
        if ([data.s isEqualToString:@"1"]) {
            [self.dataArray removeObjectAtIndex:row];
            
            NSMutableArray *nowArray = [NSMutableArray array];
            for (ZSchedulingTypeModel *model in self.dataArray) {
                if (![Common isBlankString:model.classInfoId]) {
                    [nowArray addObject:model];
                }
            }
            if ([self.delegate respondsToSelector:@selector(saveSchedulingClassDidCompleteArray:)]) {
                [self.delegate saveSchedulingClassDidCompleteArray:nowArray];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        } else {
            [SVProgressHUD showTextHUD:data.em];
        }
    }];
}
@end
